package com.whpost.service.service.cwqf;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.cwqf.HsCzyMapper;
import com.whpost.service.dao.cwqf.HsJgMapper;
import com.whpost.service.dao.cwqf.TCwqfKhzfFilesMapper;
import com.whpost.service.dao.cwqf.TCwqfKhzfMapper;
import com.whpost.service.entity.cwqf.*;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class HsCzyServices extends BaseServices<HsCzyMapper, HsCzy> {

    @Resource
    private HsJgMapper hsJgMapper;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{

            String curpage = "",pagesize="",cxmc="",sfjm="1",ksrq="",jsrq="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);

            if (null==hsCzy){
                return new ResultInfo(500,"未获取用户信息！",null);
            }

            Page<HsCzy> page = new Page<>(Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<HsCzy> hsCzyListInfo = new ListInfo<>();
            QueryWrapper<HsCzy> hsCzyQueryWrapper = new QueryWrapper<HsCzy>();

            if (!StringUtils.isEmpty(cxmc)){
                hsCzyQueryWrapper.eq("sjwh",cxmc).or().eq("name",cxmc);
            }

            hsCzyQueryWrapper.eq("1","1");

            hsCzyQueryWrapper.orderByDesc("czrq");


            IPage<HsCzy> hsCzyIPage = getBaseMapper().getHsCzyPage(page,hsCzyQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(hsCzyIPage.getTotal());
            pageInfo.setCurPage(hsCzyIPage.getCurrent());
            pageInfo.setPageSize(hsCzyIPage.getSize());
            pageInfo.setPageTotal(hsCzyIPage.getPages());

            hsCzyListInfo.setPageInfo(pageInfo);
            hsCzyListInfo.setListInfo(hsCzyIPage.getRecords());
            hsCzyListInfo.setUserId(loginId);//登录人员id，可以不设置也行

            //加密返回给前端
            if ("1".equals(sfjm)){
                ResultInfo resultInfo = new ResultInfo(200, "成功返回！",hsCzyListInfo);
                return backRtn(resultInfo,loginId);
            }else{
                //非加密,返回给其它方法使用
                return new ResultInfo(200, "成功返回！",hsCzyListInfo);
            }
        }
    }

    @Transactional
    public ResultInfo save(String loginId, List<MultipartFile> file, String data) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getDataStr(data,loginId);
            String lx="",id="",ssjg_lsh="",zgxm="",phone="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("ssjg_lsh")) {
                ssjg_lsh = jsonObject.getString("ssjg_lsh");
            }
            if (jsonObject.containsKey("phone")) {
                phone = jsonObject.getString("phone");
            }
            if (jsonObject.containsKey("zgxm")) {
                zgxm = jsonObject.getString("zgxm");
            }
            if (StringUtils.isEmpty(lx)){
                return new ResultInfo(500,"关键参数信息丢失！",null);
            }
            if (StringUtils.isEmpty(ssjg_lsh)){
                return new ResultInfo(500,"所属机构丢失！",null);
            }
            if (StringUtils.isEmpty(phone)){
                return new ResultInfo(500,"手机号丢失！",null);
            }
            if (StringUtils.isEmpty(zgxm)){
                return new ResultInfo(500,"职工姓名丢失！",null);
            }

            HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);

            if (null==hsCzy){
                return new ResultInfo(500,"用户信息丢失！",null);
            }

            if ("0".equals(hsCzy.getDoCzy())){
                return new ResultInfo(500,"没有录入的权限！",null);
            }


            HsCzy hsCzy1 = new HsCzy();



            if ("1".equals(lx)){
                hsCzy1 = getBaseMapper().selectById(id);
            }else{
                HsCzy hsCzy_old = new HsCzy();
                try {
                    hsCzy_old = getBaseMapper().getHsCzyByTel(Url.encrypt(phone));
                    if (hsCzy_old != null) {
                        return new ResultInfo(500,"该手机号用户已经存在！",null);
                    }
                } catch (Exception e) {
                    return new ResultInfo(500,"手机号解析发生错误！",null);
                }


                Long a = getMyDao().getNextSequenceValue("seq_hs_czy.nextval");

                String str = "";

                // 确保a不为null的情况下进行转换，避免空指针异常
                if (a != null) {
                    // %08d 表示将数字格式化为8位，不足8位时前面补0
                    str = String.format("%08d", a);
                }

                hsCzy1.setCode(str);
                hsCzy1.setName(zgxm);
                hsCzy1.setSsjgLsh(Long.parseLong(ssjg_lsh));
                try {
                    hsCzy1.setTel(Url.encrypt(phone));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                String result = "";

                // 校验字符串长度是否符合11位（手机号通常为11位）
                if (phone != null && phone.length() == 11) {
                    // 截取前3位 + **** + 截取后4位
                    result = phone.substring(0, 3) + "****" + phone.substring(7);
                } else {
                    // 不符合长度时可返回原字符串或做其他处理
                    result = "";
                }

                hsCzy1.setSjwh(result);
                hsCzy1.setGljg(ssjg_lsh);

                getBaseMapper().insert(hsCzy1);
            }



            return new ResultInfo(200,"登记成功！",null);
        }
    }


    public ResultInfo jgcx(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="",sfjm="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(sfjm)) sfjm = "1";
            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<HsJg> page = new Page<>(Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<HsJg> hsJgListInfo = new ListInfo<>();
            QueryWrapper<HsJg> hsJgQueryWrapper = new QueryWrapper<HsJg>();
            if (!StringUtils.isEmpty(cxmc)){
                hsJgQueryWrapper.like("name",cxmc);
            }

            hsJgQueryWrapper.eq("jb","2");

            IPage<HsJg> hsJgPage = hsJgMapper.selectPage(page,hsJgQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(hsJgPage.getTotal());
            pageInfo.setCurPage(hsJgPage.getCurrent());
            pageInfo.setPageSize(hsJgPage.getSize());
            pageInfo.setPageTotal(hsJgPage.getPages());

            hsJgListInfo.setPageInfo(pageInfo);
            hsJgListInfo.setListInfo(hsJgPage.getRecords());  // 设置去重后的列表
            hsJgListInfo.setUserId(loginId);

            //加密返回给前端
            if ("1".equals(sfjm)){
                ResultInfo resultInfo = new ResultInfo(200, "成功返回！",hsJgListInfo);
                return backRtn(resultInfo,loginId);
            }else{
                //非加密,返回给其它方法使用
                return new ResultInfo(0, "成功返回！",hsJgListInfo);
            }
        }
    }

    @Override
    public ResultInfo del(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else {
            String id="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }

            if (StringUtils.isEmpty(id)){
                return new ResultInfo(500,"要删除的数据不存在！",null);
            }
            HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);

            if ("0".equals(hsCzy.getDoCzy())){
                return new ResultInfo(500,"没有删除的权限！",null);
            }
            // 返回结果
            Map<String, Object> rtnMap = new HashMap<>();
            HsCzy hsCzy1 = getBaseMapper().selectById(id);
            if (hsCzy1!=null){
                getBaseMapper().deleteById(id);
                ResultInfo resultInfo = new ResultInfo(200, "删除成功！", rtnMap);
                return backRtn(resultInfo, loginId);

            }else{
                ResultInfo resultInfo = new ResultInfo(500, "要删除的数据不存在！", rtnMap);
                return backRtn(resultInfo, loginId);
            }
        }
    }
}